<template>
  <div class="searchBox p-rem-16 rela">
    <el-form ref="params" :model="form" class="searchBoxForm" :label-width="labelWidth" :class="showMoreSearch?'searchBoxAuto':'searchBoxHeight'">
      <el-row :gutter="10">
        <el-col v-for="(item,index) in showMoreSearchList" :key="index" :style="{'margin-top':marginTopFlag(index) ?'24px':'0','width':widthFlag(index)}" :xs="rowXs" :sm="rowSm" :md="rowMd" :lg="rowLg" :xl="rowXl">
          <el-form-item v-if="item.type === 'input'" :label="item.label" :prop="item.valueKey">
            <el-input v-model.trim="item.value" clearable :placeholder="`请输入${item.label}`" @keyup.enter.native="handleQueryFun" @clear="handleQueryFun"></el-input>
          </el-form-item>
          <el-form-item v-if="item.type == 'year'" :label="item.label">
            <el-row>
              <el-col :span="11">
                <el-form-item label="">
                  <el-date-picker v-model.trim="item.startValue" type="year" placeholder="开始年" value-format="yyyy" size="small" style="width:100%" @change="timeChangeFun(item,'start','开始年','startValue','结束年','endValue')"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label="">
                  <el-date-picker v-model.trim="item.endValue" type="year" placeholder="结束年" value-format="yyyy" size="small" style="width:100%" @change="timeChangeFun(item,'end','开始年','startValue','结束年','endValue')"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="item.type == 'month'" :label="item.label">
            <el-row>
              <el-col :span="11">
                <el-form-item label="">
                  <el-date-picker v-model.trim="item.startValue" type="month" placeholder="开始月份" value-format="yyyy-MM" size="small" style="width:100%" @change="timeChangeFun(item,'start','开始月份','startValue','结束月份','endValue')"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label="">
                  <el-date-picker v-model.trim="item.endValue" type="month" placeholder="结束月份" value-format="yyyy-MM" size="small" style="width:100%" @change="timeChangeFun(item,'end','开始月份','startValue','结束月份','endValue')"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="item.type == 'date'" :label="item.label">
            <el-row>
              <el-col :span="11">
                <el-form-item label="">
                  <el-date-picker v-model.trim="item.startValue" type="date" placeholder="开始时间" value-format="yyyy-MM-dd" size="small" style="width:100%" @change="timeChangeFun(item,'start','开始时间','startValue','结束时间','endValue')"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label="">
                  <el-date-picker v-model.trim="item.endValue" type="date" placeholder="结束时间" value-format="yyyy-MM-dd" size="small" style="width:100%" @change="timeChangeFun(item,'end','开始时间','startValue','结束时间','endValue')"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="item.type == 'select'" :label="item.label">
            <el-select v-model.trim="item.value" clearable filterable :multiple="item.multiple" :placeholder="`请选择${item.label}`">
              <el-option
                v-for="items in item.typeData"
                :key="items.dictValue"
                :label="items.dictLabel"
                :value="items.dictValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="item.type == 'number'" :label="item.label">
            <el-row>
              <el-col :span="11">
                <el-form-item label="">
                  <el-input
                    v-model.trim="item.startValue"
                    v-input.float="{'float':item.precision,'min':item.min,'max':item.max}"
                    placeholder="请输入"
                    @focus="focusNumBerFun($event)"
                    @blur="blurNumBerFun($event,item.precision,item,'startValue')"
                    @keyup.enter.native="handleQueryFun"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label="">
                  <el-input
                    v-model.trim="item.endValue"
                    v-input.float="{'float':item.precision,'min':item.min,'max':item.max}"
                    placeholder="请输入"
                    @focus="focusNumBerFun($event)"
                    @blur="blurNumBerFun($event,item.precision,item,'endValue')"
                    @keyup.enter.native="handleQueryFun"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="item.type == 'treeselect'" :label="item.label">
            <treeselect v-model="item.value" :loadOptions="({ action, parentNode, callback })=>item.loadOptions==true ? loadOptions({ action, parentNode, callback}, item.url,item.normalizerObj) : loadOptions({})" no-options-text="暂无数据" noResultsText="未搜索到内容" noChildrenText="暂无下级分类" :options="item.typeData" :appendToBody="true" :show-count="false" :placeholder="`请选择${item.label}`" />
          </el-form-item>
          <el-form-item v-if="item.type == 'cascader'" :label="item.label">
            <el-row class="flex flex-nowrap">
              <el-col v-for="(cascaderItem,ind) in item.typeDataOptions" :key="ind" :span="24/item.typeDataOptions.length" :class="ind == item.typeDataOptions.length - 1 ? '' : 'p-rem-r-5'">
                <el-select v-model.trim="cascaderItem.value" @change="(val)=>regionChange(item,index,val,ind)">
                  <el-option
                    v-for="items in item[cascaderItem.name+'Options']"
                    :key="items.dictValue"
                    :label="items.dictLabel"
                    :value="items.dictValue"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>

          </el-form-item>
        </el-col>
        <el-col :xs="rowXs" :sm="rowSm" :md="rowMd" :lg="rowLg" :xl="rowXl" :style="{'margin-top':showMoreSearch&&(queryDataLength-1)<queryDataDataLength?'24px':'0'}">
          <el-form-item label-width="0px" label="" class="bao_seniorSearch">
            <el-button type="primary" size="small" search @click="handleQueryFun">查询</el-button>
            <el-button size="small" @click="handleResetFun">重置</el-button>
            <el-button v-if="(queryDataLength-1)<queryDataDataLength" type="text" :icon="!showMoreSearch?'el-icon-arrow-down':'el-icon-arrow-up'" @click="showMoreSearchFun()">{{ !showMoreSearch?'展开':'收起' }}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import resizeViewConfig from '@/utils/commonUtils/resizeViewConfig'// 全局更改大小
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { commonMixins } from '@/mixins/publicMixins/commonMixins'
import { methodGetApi } from '@/api/publicApi'

export default {
  mixins: [commonMixins],
  components: { Treeselect },
  props: {
    queryData: Object,
    labelLength: {
      type: Number,
      default: 4
    }// lable的长度
  },
  inject: {
    listQueryParams: {
      default: () => ({})
    }
  },
  data() {
    return {
      // style: {}, // 样式问题
      queryDataLength: 3, // 根据浏览器的可视图的宽度改变初始值 (1920)
      rowXs: 12, // <768px响应式栅格数或者栅格属性对象
      rowSm: 12, // ≥768px 响应式栅格数或者栅格属性对象
      rowMd: 8, // ≥992px 响应式栅格数或者栅格属性对象
      rowLg: 6, // ≥1200px 响应式栅格数或者栅格属性对象
      rowXl: 6, // ≥1920px 响应式栅格数或者栅格属性对象
      form: {},
      showMoreSearch: false,
      queryJumpData: null,
      showSeniorSearch: false,
      newData: {},
      labelWidth: ((this.labelLength * 1.4 + 1.2 + 0.2 + 'rem')), // label的宽度
      showMoreSearchList: [],
      queryDataDataList: [],
      queryDataDataLength: 0 // 可展示的长度
    }
  },
  // updated() {
  //   console.log(11111)
  // },
  created() {
    this.queryDataDataList = []
    this.queryData.data.forEach(async(element) => {
      if (element.multiple) {
        element.value = []
      }
      if (element.type !== 'default') {
        this.queryDataDataList.push(element)
        this.queryDataDataLength++
      }
      if (element.type === 'treeselect') {
        element.typeData = []
        this.getTreeSelectLazyMixins('', element.getUrl, element.normalizerObj).then(res => {
          element.typeData = res
        })
      }
      if (element.type === 'cascader') {
        // this.cascaderFun(element)
        element.typeDataOptions.forEach(elem => {
          element[elem.name + 'Options'] = []
        })
        methodGetApi(element.getUrl, element.getUrlData).then(res => {
          element[element.typeDataOptions[0].name + 'Options'] = []
          const data = res.data || res.rows
          data.forEach(eleme => {
            element[element.typeDataOptions[0].name + 'Options'].push({
              dictValue: eleme[element.getUrlDictValue],
              dictLabel: eleme[element.getUrlDictLabel]
            })
          })
        })
      }
      if (element.type === 'select') {
        if(element.typeData.length == 0){
          if (element.dataType === 'dicts') {
            this.getDicts(element.getDicts).then((response) => {
              element.typeData = response.data
            })
          } else {
            await methodGetApi(element.getUrl, element.getUrlData).then(res => {
              element.typeData = []
              const data = res.data || res.rows
              data.forEach(eleme => {
                if (element.getUrlListBool === true) {
                  element.typeData.push({
                    dictValue: eleme,
                    dictLabel: eleme
                  })
                } else {
                  element.typeData.push({
                    dictValue: eleme[element.getUrlDictValue],
                    dictLabel: eleme[element.getUrlDictLabel]
                  })
                }
              })
            })
          }
        }
      }
    })
  },
  mounted() {
    this.handleResize()
    window.addEventListener('resize', this.handleResize)
    this.handleQueryFun()
  },

  methods: {

    /**
     * @description: 二，三，四……级联动change事件
     * @Author: baoxuhui
     * @return {*}
     */
    regionChange(element, index, val, ind) {
      const numsArry = []
      const nums = element.typeDataOptions.length
      for (let i = 1; i <= nums; i++) {
        numsArry.push(i)
      }
      numsArry.forEach(num => {
        if (ind + 1 < num) {
          element[element.typeDataOptions[num - 1].name + 'Options'] = []
          this.$set(this.showMoreSearchList[index].typeDataOptions[num - 1], 'value', null)
          element[element.typeDataOptions[num - 1].value] = null
        }
      })
      this.$set(this.showMoreSearchList, index, element)
      methodGetApi(element.getUrl, { [element.getUrlDataKey]: val }).then(res => {
        if (ind < element.typeDataOptions.length - 1) {
          const data = res.data || res.rows
          data.forEach(eleme => {
            element[element.typeDataOptions[ind + 1].name + 'Options'].push({
              dictValue: eleme[element.getUrlDictValue],
              dictLabel: eleme[element.getUrlDictLabel]
            })
          })
          this.$set(this.showMoreSearchList, index, element)
        }
      })
    },

    // 二，三，四……级联动 el-cascader加载动态数据的方法
    // lazyLoad(node, resolve, element) {
    //   console.log(node)
    //   setTimeout(async() => {
    //   //   // 通过调用resolve将子节点数据返回，通知组件数据加载完成
    //     const getUrlData = { [node.level === 0 ? element.getUrlDataKey : element.getUrlNodeKey]: node.value ? node.value : element.getUrlDataValue }
    //     await methodGetApi(element.getUrl, getUrlData).then(res => {
    //       const data = res.data || res.rows
    //       data.forEach(eleme => {
    //         eleme.value = eleme[element.getUrlDictValue]
    //         eleme.label = eleme[element.getUrlDictLabel]
    //         eleme.leaf = node.level >= 2
    //       })
    //       resolve(data)
    //     })
    //   }, 1000)
    // },
    /**
     * @description: 判断是否需要加margin-top
     * @Author: baoxuhui
     * @param {*} index
     * @return {*}
     */
    marginTopFlag(index) {
      if (this.showMoreSearch) {
        if (this.queryDataLength < this.queryDataDataLength) {
          if (index + 1 <= this.queryDataLength) {
            return false
          } else {
            return true
          }
        }
      } else {
        return false
      }
    },
    /**
     * @description: 宽度判断
     * @Author: baoxuhui
     * @param {*} index
     * @return {*}
     */
    widthFlag(index) {
      if (this.showMoreSearchList[index].type === 'cascader') {
        return '50%'
      }
    },
    /**
     * @description: 展开/收起
     * @description:
     * @Author: baoxuhui
     * @return {*}
     */
    showMoreSearchFun() {
      this.showMoreSearch = !this.showMoreSearch
      if (this.showMoreSearch) {
        this.showMoreSearchList = this.queryDataDataList
      } else {
        this.handleResize()
      }
      this.$nextTick(() => {
        resizeViewConfig()
      })
    },
    /**
     * @description: 根据浏览器的可视图的宽度改变
     * @Author: baoxuhui
     * @return {*}
     */
    handleResize() {
      this.showMoreSearchList = []
      this.showMoreSearch = false
      const clientWidth = document.documentElement.clientWidth
      // showMoreSearch?queryData.data:queryData.data.slice(0,queryDataLength)
      if (clientWidth >= 1920) {
        this.queryDataLength = (24 / this.rowXl)
      } else if (clientWidth < 1920 && clientWidth >= 1200) {
        this.queryDataLength = (24 / this.rowLg)
      } else if (clientWidth < 1200 && clientWidth >= 992) {
        this.queryDataLength = (24 / this.rowMd)
      } else if (clientWidth < 992 && clientWidth >= 768) {
        this.queryDataLength = (24 / this.rowSm)
      } else if (clientWidth < 768) {
        this.queryDataLength = (24 / this.rowXs)
      }
      // console.log(clientWidth)
      // console.log(this.queryDataDataLength)
      // console.log(this.queryData.data)
      // console.log(this.queryDataDataList)
      // console.log(this.queryDataLength)

      this.queryDataDataList.forEach((element, index) => {
        if (index + 1 <= this.queryDataLength - 1) {
          this.showMoreSearchList.push(element)
        }
      })
    },

    // 查询
    handleQueryFun(data) {
      // (this.queryData.data)
      // console.log(this.queryData.data)
      this.queryData.data.forEach(element => {
        if (element.type === 'input' || element.type === 'select' || element.type === 'treeselect' || element.type === 'default') {
          this.newData[element.valueKey] = element.value
        } else if (element.type === 'cascader') {
          const cascaderData = []
          element.typeDataOptions.forEach((ele, ind) => {
            console.log(ele)
            if (ele.value) {
              cascaderData.push(ele.value)
            }
          })
          this.newData[element.valueKey] = cascaderData.length > 0 ? cascaderData.toString() : null
          // this.newData[element.valueKey] = element.value ? element.value.toString() : element.value
        } else {
          this.newData[element.startKey] = element.startValue
          this.newData[element.endKey] = element.endValue
        }
      })
      if (this.queryData.queryParams) {
        this.newData.pageNum = 1
        this.newData.pageSize = this.queryData.queryParams.pageSize
        //    this.queryData.queryParams.pageNum = 1
        // this.queryData.queryParams.pageSize = this.queryData.queryParams.pageSize
      }

      Object.assign(this.newData, data)
      this.$emit('getQuery', this.newData)
    },

    // 重置
    handleResetFun() {
      this.resetFields()
      if (this.listQueryParams.resetOtherQueryParams) {
        this.listQueryParams.resetOtherQueryParams()// 清除列表的额外条件
      }
    },
    // 重置表单
    resetFields() {
      this.newData = {}
      // 清除该组件的值
      this.queryData.data.forEach((element, index) => {
        if (element.type === 'input' || element.type === 'select' || element.type === 'treeselect') {
          this.queryData.data[index].value = ''
          delete this.queryData.data[index].value
        } else if (element.type === 'default') {
          if (this.queryData.queryParams) {
            this.newData[element.valueKey] = element.value
            this.queryData.queryParams[element.valueKey] = element.value
          }
        } else if (element.type === 'cascader') {
          this.queryData.data[index].typeDataOptions.forEach((ele, ind) => {
            if (ind > 0) {
              this.queryData.data[index][ele.name + 'Options'] = []
            }

            ele.value = null
          })
        } else {
          this.queryData.data[index].startValue = null
          this.queryData.data[index].endValue = null
          delete this.queryData.data[index].startValue
          delete this.queryData.data[index].endValue
        }
      })

      if (this.queryData.queryParams) {
        // 对列表的查询初始化
        this.newData.pageNum = 1
        this.newData.pageSize = this.queryData.queryParams.pageSize
        this.queryData.queryParams.pageNum = 1
        this.queryData.queryParams.pageSize = this.queryData.queryParams.pageSize
        // {
        //   pageNum: 1,
        //   pageSize: this.queryData.queryParams.pageSize
        // }
        // this.queryData.queryParams = {
        //   pageNum: 1,
        //   pageSize: this.queryData.queryParams.pageSize
        // }
      }
      this.$refs['params'].resetFields()
      // console.log(this.newData)
      this.$emit('getQuery', this.newData)
    }

  }
}
</script>
